# _*_ coding:utf-8 _*_
# @Time  : 2023.06.26
# @Author: zizlee
import random
import re


class StringUtils:

    @classmethod
    def full2half(cls, u_string):
        # """ 全角转半角 """
        r_string = ""
        for uchar in u_string:
            inside_code = ord(uchar)
            if inside_code == 12288:  # 全角空格直接转换
                inside_code = 32
            elif 65281 <= inside_code <= 65374:  # 全角字符（除空格）根据关系转化
                inside_code -= 65248
            else:
                pass
            r_string += chr(inside_code)
        return r_string

    @classmethod
    def random_string(cls, length: int = 6, alpha: bool = False, u_alpha: bool = False):
        alpha_str = 'abcdefghijklmnopqrstuvwxyz'
        u_alpha_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        nums = '1234567890'
        ret_str = nums
        if alpha:
            ret_str += alpha_str
        if u_alpha:
            ret_str += u_alpha_str
        result = ''
        for _ in range(length):
            result += random.choice(ret_str)
        return result


class SequenceDataUtils:
    @classmethod
    def list2tree(cls, data: list, pkey: str, ckey: str,  fvalue: str):
        # pkey: parent key
        # ckey: compare key
        # fvalue: first value
        # list2tree(data, pkey, ckey, menu[ckey])
        return [dict(menu, **{'children': cls.list2tree(data, pkey, ckey, menu[ckey])}) for menu in
                [m for m in data if str(m[pkey]) == str(fvalue)]]


class DatlibUtils:
    @classmethod
    def formula2ids(cls, formula: str):
        iid_list = re.sub(r'[*/+-]', ',', re.sub(r'[()]', '', formula)).split(',')
        return [int(i.replace('i', '')) for i in iid_list if i.startswith('i')]

    @classmethod
    def public_date_range_frequency(cls, index_objs: list):
        start_date, end_date = None, None
        frequency = None
        frequency_list = []
        for idx in index_objs:
            if start_date is None:
                start_date = idx['start_date']
            else:
                if idx['start_date'] > start_date:
                    start_date = idx['start_date']
            if end_date is None:
                end_date = idx['end_date']
            else:
                if idx['end_date'] < end_date:
                    end_date = idx['end_date']
            frequency_list.append(idx['frequency'])

        for f in ['日', '周', '月', '季', '年']:
            if f in frequency_list:
                frequency = f
                break
        return [start_date, end_date, frequency]






